package mysql

import (
	"crypto/md5"
	"encoding/hex"
	"personal-blog/models"
	"personal-blog/pkg/snowflake"
	"time"
)

const secret = "wutianjiao.com"

//密码加密
func encryptPassword(data []byte) (result string) {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum(data))
}

//注册
func Register(user *models.User) (err error) {
	u := db.Where("user_name = ?", user.UserName).Find(user)

	if u.RowsAffected > 0 {
		// 用户已存在
		return ErrorUserExit
	}
	//生成user_id
	userID, err := snowflake.GetID()
	if err != nil {
		return ErrorGenIDFailed
	}
	// 生成加密密码
	password := encryptPassword([]byte(user.Password))
	// 把用户插入数据库
	db.Table("users").Create(map[string]interface{}{
		"user_id": userID, "password": password, "user_name": user.UserName, "created_at": time.Now(), "updated_at": time.Now(),
	})
	return
}

//登录
func Login(user *models.User) (err error) {
	originPassword := user.Password
	u := db.Table("users").Where("user_name = ?", user.UserName).Find(&user)
	if u.RowsAffected == 0 {
		// 用户不存在
		return ErrorUserNotExit
	}
	var use models.User
	db.Table("users").Select("password").Where("user_name = ?", user.UserName).Find(&use)
	password := encryptPassword([]byte(originPassword))
	if use.Password != password {
		return ErrorPasswordWrong
	}
	return
}

//得到用户列表
func GetUserList() (userList []*models.User, err error) {
	db.Table("users").Select("user_name").Find(&userList)
	return
}
